import React, { PureComponent } from 'react';
import { Popconfirm, Button, Popover } from 'antd';
import { connect } from 'dva';

class PateoAuthButtons extends PureComponent {
  render() {
    const {
      btns,
      max = 2,
      menu: { permissions },
      pathname,
    } = this.props;
    // 按钮的样式
    const btnProps = {
      size: 'small',
      ghost: true,
      type: 'primary',
      style: { marginLeft: 12 },
    };
    const authbtns = btns
      .filter((item: any) => {
        return permissions.includes(pathname + '/' + item.auth);
      })
      .filter((item: any) => !item.hide); // 经过权限过滤之后的数据
    // 普通的button
    const simpleButton = (item: any) => (
      <Button
        key={item.key}
        onClick={item.onConfirm}
        disabled={item.disabled || false}
        {...btnProps}
        type={item.type ?? btnProps.type}
      >
        {item.title}
      </Button>
    );
    // 带气泡框的button
    const popconfirmButton = item => (
      <span key={item.key} onClick={e => e.stopPropagation()}>
        <Popconfirm
          key={item.key}
          title={item.message}
          onConfirm={item.onConfirm}
          disabled={item.disabled || false}
        >
          <Button
            key={item.key}
            disabled={item.disabled || false}
            onClick={e => e.stopPropagation()}
            {...btnProps}
          >
            {item.title}
          </Button>
        </Popconfirm>
      </span>
    );
    // 浮动的button
    const popoverButton = (authbtns: any) => (
      <Popover
        key="popover"
        placement="left"
        content={authbtns.map((item: any) => {
          return item.Popconfirm ? popconfirmButton(item) : simpleButton(item);
        })}
        title={false}
      >
        <Button key="extra" {...btnProps}>
          更多 &lt;
        </Button>
      </Popover>
    );
    const authButtons =
      authbtns.length > max + 1
        ? authbtns
            .slice(0, max)
            .map((item: any) => {
              return item.Popconfirm ? popconfirmButton(item) : simpleButton(item);
            })
            .concat(popoverButton(authbtns.slice(max)))
        : authbtns.map((item: any) => {
            return item.Popconfirm ? popconfirmButton(item) : simpleButton(item);
          });
    return authButtons;
  }
}

export default connect(({ menu }) => ({
  menu,
}))(PateoAuthButtons);
